<template>
  <view class="familyItem">
    <checkbox-group @change="checkboxChange">
      <view v-for="(item, index) in familyItem" :key="index" class="list">
        <view>
          <label class="displayBlock">
            <view v-if="maxLen > -1" class="checkBtn">
              <checkbox
                :id="index"
                :value="item.memberId"
                :checked="checkedValues.includes(item.memberId) || item.relation === 1"
                :disabled="haveAuthedUserList.includes(item.memberId) || item.relation === 1"
              />
            </view>
            <view>
              <span :class="['head', index % 2 === 0 ? 'listOdd' : null]"><img :src="item.icon" /></span>
              <span class="name floatLeft">{{ item.memberName }}</span>
              <span :class="['relation floatLeft', index === 0 ? null : 'origin']">{{ item.relationName }}</span>
            </view>
            <view class="clear"></view>
          </label>
        </view>
        <view class="rightEdit">
          <!-- <span v-if="index > 0 && !fromPage" class="delete" @click="deleteFun(item)"
            ><img :src="require('../images/icons/delete.png')"
          /></span> -->
          <span class="edit" @click="editFun(item)"><img :src="require('../images/icons/edit.png')" /></span>
        </view>
      </view>
    </checkbox-group>
    <view v-if="familyItem && familyItem.length === 0" class="zwsj"> </view>
    <!-- <fixedBottomButton> -->
    <view class="uni-btn-v">
      <view class="butStyle" @click="addMemberFun"><span>新建</span></view>
    </view>
    <!-- </fixedBottomButton> -->
  </view>
</template>

<script>
const nr =
  'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/wanhuhealth-small-program/wanhu-mini-welfare/welfare/index/man.png';
const fm =
  'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/wanhuhealth-small-program/wanhu-mini-welfare/welfare/index/parent.png';
const nvr =
  'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/wanhuhealth-small-program/wanhu-mini-welfare/welfare/index/woman.png';
const zn =
  'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/wanhuhealth-small-program/wanhu-mini-welfare/welfare/index/child.png';
const fq =
  'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/wanhuhealth-small-program/wanhu-mini-welfare/welfare/index/father.png';
const mq =
  'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/wanhuhealth-small-program/wanhu-mini-welfare/welfare/index/mother.png';
const nver =
  'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/wanhuhealth-small-program/wanhu-mini-welfare/welfare/index/der.png';
const erzi =
  'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/wanhuhealth-small-program/wanhu-mini-welfare/welfare/index/son.png';
import { getFamilyMember, deleteFamilyMember, getUserInfoByPatientId } from '@/api/join.js';
import { getAuthMedicOrderInfo, postAuthMedicOrder } from '@/api/videoDoctor.js';
import { tongji } from '@/utils/tools';
export default {
  data() {
    return {
      loadingImg: true,
      familyItem: null,
      choseNum: false,
      maxLen: -1,
      loginPatientId: wx.getStorageSync('patientid') || '',
      haveAuthedUserList: [],
      checkedValues: [],
      fromPage: null
    };
  },
  onLoad: function (option) {
    if (option && option.maxLen) {
      this.maxLen = Number(option.maxLen);
    }
    if (option && option.patientId) {
      this.loginPatientId = option.patientId;
    }
    if (option && option.from) {
      this.fromPage = option.from;
      wx.setNavigationBarTitle({
        title: '选择家庭成员'
      });
    }
  },
  onShow() {
    this.getMainData();
  },
  onUnload: function () {
    this.loadingImg = true;
    this.familyItem = null;
    this.choseNum = true;
    this.maxLen = -1;
    this.haveAuthedUserList = [];
  },

  methods: {
    async getMainData() {
      let { data } = await getFamilyMember(this.loginPatientId);
      if (this.fromPage) {
        let res = await getAuthMedicOrderInfo(this.loginPatientId);
        if (res.code === 0 && res.data) {
          this.haveAuthedUserList = res.data.users.map((item) => {
            return item.patientId;
          });
          this.checkedValues = this.haveAuthedUserList;
        }
        if (res.code !== 0) {
          uni.showModal({
            content: '获取用户家庭卡授权报错'
          });
        }
      }
      let brd = [];
      let fmd = [];
      let pod = [];
      let znd = [];
      let fmhead = fm;
      let znhead = zn;
      this.familyItem = [];
      data.forEach((item) => {
        switch (item.relation) {
          case 1:
            item.relationName = '本人';
            brd.push(item);
            item.icon = item.sex === 0 ? nvr : nr;
            break;
          case 2:
            item.relationName = '配偶';
            pod.push(item);
            item.icon = item.sex === 1 ? nr : nvr;
            break;
          case 3:
            item.relationName = '父母';
            fmd.push(item);
            if (item.sex || item.sex === 0) {
              fmhead = item.sex === 0 ? mq : fq;
            }
            item.icon = fmhead;
            break;
          default:
            item.relationName = '子女';
            znd.push(item);
            if (item.sex || item.sex === 0) {
              znhead = item.sex === 0 ? nver : erzi;
            }
            item.icon = znhead;
        }

        return item;
      });
      const wxUserInfo = wx.getStorageSync('rawData') ? JSON.parse(wx.getStorageSync('rawData')) : null;
      if (wxUserInfo && wxUserInfo.avatarUrl && brd.length > 0) {
        brd[0].icon = wxUserInfo.avatarUrl;
      }
      this.familyItem = [...brd, ...fmd, ...pod, ...znd];
      if (this.familyItem.length < 1) {
        this.getLoginUserInfoFun();
      }
    },
    async getLoginUserInfoFun() {
      const { data } = await getUserInfoByPatientId(this.loginPatientId);
      const brData = {
        relationName: '本人',
        relation: 1,
        memberName: data.name,
        sex: data.sex || 1,
        memberId: data.patientId,
        icon: nr
      };
      this.familyItem.push(brData);
      const wxUserInfo = wx.getStorageSync('rawData') ? JSON.parse(wx.getStorageSync('rawData')) : null;
      if (wxUserInfo && wxUserInfo.avatarUrl) {
        this.familyItem[0].icon = wxUserInfo.avatarUrl;
      }
    },
    authUser() {
      let targetUser = this.familyItem.find((item) => {
        return item.memberId === this.checkedValues.slice(-1)[0];
      });
      if (targetUser) {
        let postData = {
          toUserId: targetUser.memberId,
          relation: targetUser.relation
        };
        postAuthMedicOrder(this.loginPatientId, postData).then((res) => {
          if (res.code === 0) {
            uni.showToast({
              title: '授权成功'
            });
            this.$wxPromise.navigateBack();
          } else {
            // 取消选中
            this.checkedValues.pop();

            uni.showModal({
              content: res.message || '授权失败，请联系管理员',
              success: () => {
                this.$wxPromise.navigateBack();
              }
            });
          }
        });
      } else {
        // 取消选中
        this.checkedValues.pop();
        uni.showModal({
          title: '用户id不存在'
        });
      }
    },
    checkboxChange(e) {
      const values = e.detail.value;
      this.checkedValues = values;
      // let selectedPatientId = values[values.length - 1];
      uni.showModal({
        title: '提示',
        content: '请确认授权该用户使用视频医生？',
        success: (res) => {
          if (res.confirm) {
            this.authUser();
          }
          if (res.cancel) {
            this.checkedValues.pop();
          }
        },
        fail: () => {
          console.log('失败');
        }
      });
    },
    deleteFun(item) {
      const self = this;
      uni.showModal({
        title: '解除关系',
        content: `确定解除您跟“${item.memberName}”之间的“${item.relationName}”关系吗？`,
        success: function (res) {
          if (res.confirm) {
            self.deleteFamilyFun(item.memberId);
          }
        }
      });
    },
    async deleteFamilyFun(memberId) {
      const { code } = await deleteFamilyMember(this.loginPatientId, memberId);
      if (code === 0) {
        this.getMainData();
        uni.showToast({ title: '解绑成功', icon: 'none' });
      }
    },
    editFun(item) {
      this.goPunchPage(item.sex, item.memberId, item.relation);
    },
    addMemberFun() {
      this.goPunchPage(this.familyItem[0].sex);
      tongji('326c1752-4305-49b2-8c55-3eb4b588d129');
    },
    goPunchPage(sex, id, identity) {
      this.$wxPromise.navigateTo({
        url: `/pagesC/familyMember/editOrAdd?sex=${sex}&memberId=${id || ''}&identity=${identity || ''}`
      });
    }
  }
};
</script>
<style lang="scss">
.familyItem {
  padding-bottom: calc(88rpx + 40rpx + constant(safe-area-inset-bottom) + 60rpx);
  padding-bottom: calc(88rpx + 40rpx + env(safe-area-inset-bottom) + 60rpx);
  @supports not (constant(safe-area-inset-bottom)) {
    padding-bottom: 180rpx;
  }
  padding-bottom: 220rpx !important;
  .list {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 28rpx;
    position: relative;
    min-height: 60rpx;
    margin: 24rpx;
    .displayBlock {
      .checkBtn {
        position: absolute;
        left: 16rpx;
        top: 50%;
        width: 52rpx;
        height: 52rpx;
        display: inline-block;
        margin-top: -26rpx;
        transform: scale(0.7);
      }
      .head {
        width: 60rpx;
        height: 60rpx;
        position: absolute;
        left: 64rpx;
        top: 50%;
        margin-top: -40rpx;
        display: inline-block;
        border-radius: 120rpx;
        overflow: hidden;
        background: #feecd7;
        padding: 10rpx;
        img {
          width: 60rpx;
          height: 60rpx;
          border-radius: 56rpx;
        }
      }
      .listOdd {
        background: #e5edfe !important;
      }
      .name {
        font-size: 36rpx;
        font-weight: bold;
        margin: 24rpx 30rpx 0 160rpx;
        max-width: 200rpx;
      }
      .relation {
        display: inline-block;
        padding: 0rpx 10rpx;
        background-color: #f34e1c;
        font-size: 24rpx;
        color: #fff;
        border-radius: 20rpx 20rpx 20rpx 0;
        margin-top: 32rpx;
      }
      .origin {
        background: rgba(243, 78, 28, 0.3) !important;
        color: #f34e1c;
      }
    }
    .rightEdit {
      position: absolute;
      right: 10rpx;
      top: 50%;
      width: 174rpx;
      height: 52rpx;
      text-align: right;
      display: inline-block;
      margin-top: -20rpx;
      .delete {
        padding: 16rpx;
        margin-right: 20rpx;
        img {
          width: 40rpx;
          height: 40rpx;
        }
      }
      .edit {
        padding: 16rpx;
        img {
          width: 40rpx;
          height: 40rpx;
        }
      }
    }
  }
}
.uni-btn-v {
  margin: 24rpx;
  .butStyle {
    display: block;
    text-align: center;
    line-height: 88rpx;
    width: 702rpx;
    height: 88rpx;
    border: 2rpx solid #f34e1c !important;
    background: #fff;
    color: #f34e1c;
    opacity: 1;
    border-radius: 24rpx;
    font-size: 36rpx;
    span {
      position: relative;
      font-size: 36rpx;
      padding-left: 50rpx;
      text-align: center;
    }
    span:before {
      position: absolute;
      content: '+';
      font-weight: bold;
      border: 2rpx solid #f34e1c;
      left: -20rpx;
      top: 5rpx;
      width: 40rpx;
      height: 40rpx;
      line-height: 34rpx;
      text-align: center;
      display: inline-block;
      border-radius: 100rpx;
      box-sizing: border-box;
    }
  }
}

.displayBlock {
  display: block;
  min-height: 100rpx;
}
.floatLeft {
  float: left;
}
.clear {
  clear: both;
}
.pointNone {
  pointer-events: none;
  opacity: 0.5;
}
.noData {
  text-align: center;
  padding: 40rpx;
}
</style>
<style>
page {
  background-color: #f4f4f4;
}
.uni-btn-v button {
  border: none !important;
}
button:after {
  border: none !important;
}
.phcolor {
  color: rgba(0, 0, 0, 0.3);
}
</style>
